# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config
from action.user.base import userAction
from model.info import info
from model.category import category
from model.album import album
from model.image import image

'''
user controller: producing info useristration views.
'''
class refererAction(userAction):
    def __init__(self, name = '信息管理'):
        userAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        elif name == 'listForBatchDel':
            return self.listForBatchDel()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'modify':
            return self.modify()
        elif name == 'deleteBatch':
            return self.deleteBatch()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {'owner':self.userid}
        infoObj = info()
        listData = infoObj.getOne('COUNT(*) AS `total`', condition)
        totalCount = listData['total']
        infoList = infoObj.getList('*', condition, 'id desc', str(offset) + ',' + str(count))

        pageString = self.getPageStr(self.makeUrl('/user/info/list'), page, count, totalCount)
        self.privData['INFO_LIST'] = infoList
        self.privData['PAGE_STRING'] = pageString

        categoryList = category().getList('*', {})
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:
            self.privData['CATEGORY_LIST'][i['id']] = i['name']
        return self.display('infoList')

    def listForBatchDel(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {'owner':self.userid}
        infoObj = info()
        listData = infoObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        infoList = infoObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/user/info/list', page, count, totalCount)
        self.privData['INFO_LIST'] = infoList
        self.privData['PAGE_STRING'] = pageString

        categoryList = category().getList('*', {})
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']

        return self.display('infoBatchDel')

    def delete(self):
        inputParams = self.getInput()

        try:
            condition = {'id': int(inputParams['id'])}
            info().delete(condition)
        except Exception, e:
            return self.error(msg='信息删除失败: %s' % e, url=self.makeUrl('/user/info/list'))

        return self.success(msg='信息删除成功', url=self.makeUrl('/user/info/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            info().delete(condition)
        except Exception, e:
            return self.error(msg='信息删除失败: %s' % e, url=self.makeUrl('/user/info/list'))

        return self.success(msg='信息删除成功', url=self.makeUrl('/user/info/list'))


    def add(self):
        categoryList = self.getInfoCats();

        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        condition = {'owner':self.userid}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        self.privData['IMG_URL_LIST'] = {};
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('infoAdd')
    
    def modify(self):
        userInput= self.getInput()

        try: 
            desc =  userInput['desc'] if userInput['desc'] else userInput['content']   
            data={
                'content':      self.htmlunquote(userInput['content']),
                'name':         userInput['name'],
                'desc':         self.subText(self.htmlunquote(desc), 0, 32),
                'status':       userInput['status'],
                'category':     int(userInput['category']),
                'thumbnail':    int(userInput['thumbnail']),
                'owner':        int(self.userid),
            }

            condition={'id': int(userInput['id'])}
            info().update(data, condition)
        except Exception, e:
            return self.error(msg = '信息修改失败: %s' % e, url=self.makeUrl('/user/info/list'))

        return self.success('信息修改成功', url=self.makeUrl('/user/info/list'))

    def edit(self):
        inputParams = self.getInput()
        condition={'id': int(inputParams['id'])}
        infoObj = info().getOne('*', condition)
        if not infoObj:
            return self.error(msg = '信息不存在')
        self.privData['INFO_INFO'] = infoObj

        categoryList = self.getInfoCats();
        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        condition = {'owner':self.userid}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        self.privData['IMG_URL_LIST'] = {};
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 
                self.privData['IMG_URL_LIST'][img['id']] = self.imageUrl(img['id'])

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = infoObj['thumbnail']
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('infoEdit')


    def save(self):
        userInput= self.getInput()
        import time
        currentDate = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())

        try:
            desc = userInput['desc'] if userInput['desc'] else userInput['content']
            data = {
                'content':      self.htmlunquote(userInput['content']),
                'desc':         self.subText(self.htmlunquote(desc), 0, 32),
                'name':         userInput['name'],
                'createTime':   currentDate,
                'status':       int(userInput['status']),
                'category':     int(userInput['category']),
                'thumbnail':    int(userInput['thumbnail']),
                'owner':        int(self.userid),
            }
            info().insert(data)
        except Exception, e:    
            return self.error(msg = '信息保存失败: %s' % e, url=self.makeUrl('/user/info/list'))

        return self.success('信息保存成功', url=self.makeUrl('/user/info/list'))
